﻿using RayD.Repository;
using System;
using System.Collections.Generic;
using System.Text;
using RayD.Repository.Core;
using RayD.Repository.Entites.SystemModule;
using RayD.Core;
using Dapper;
using System.Data;
using Newtonsoft.Json.Linq;
using System.Linq;
using System.IO;

namespace RayD.App.SystemModule
{
    public class UserApp
    {
        #region 构造函数注入
        private IRepository BaseRepository;
        private ManaframeApp _manaframe;
        private DepartmentApp _Department;
        public UserApp(IRepository repository, ManaframeApp manaframe, DepartmentApp Department)
        {
            this.BaseRepository = repository;
            this._manaframe = manaframe;
            this._Department = Department;
        }
        #endregion

        #region 获取数据

        /// <summary>
        /// 获取列表数据
        /// </summary>
        /// <param name="queryJson">查询条件</param>
        /// <returns></returns>
        public IEnumerable<UserEntity> GetList(string queryJson)
        {
            var expression = LinqExtensions.True<UserEntity>();

            var queryParam = queryJson.ToJObject();
            if (!queryParam["B_ManaframeId"].IsEmpty())
            {
                expression = expression.And(c => c.B_ManaframeId == queryParam["B_ManaframeId"].ToString());
            }
            if (!queryParam["B_DepartmentId"].IsEmpty())
            {
                expression = expression.And(c => c.B_DepartmentId == queryParam["B_DepartmentId"].ToString());
            }
            if (!queryParam["B_Account"].IsEmpty())
            {
                expression = expression.And(c => c.B_Account.Contains(queryParam["B_Account"].ToString()));
            }
            if (!queryParam["B_RealName"].IsEmpty())
            {
                expression = expression.And(c => c.B_RealName.Contains(queryParam["B_RealName"].ToString()));
            }
            if (!queryParam["B_CreateDate"].IsEmpty())
            {
                expression = expression.And(c => c.B_CreateDate >= queryParam["B_CreateDate"][0].ToDate() && c.B_CreateDate <= queryParam["B_CreateDate"][1].ToDate());
            }
            expression = expression.And(c => c.B_SecurityLevel != 1);   //排除超管用户
            /*关联架构*/
            var userInfo = AuthenticationHelper.LoginUserInfo;
            if (!userInfo.isSystem)
            {
                var manaframeIds = _manaframe.GetSubNodes(userInfo.manaframeId);
                expression = expression.And(c => manaframeIds.IndexOf(c.B_ManaframeId) >= 0);
            }
            return BaseRepository.IQueryable(expression).ToList();
        }
        /// <summary>
        /// 获取分页列表数据
        /// </summary>
        /// <param name="queryJson">查询条件</param>
        /// <param name="pagination">分页参数</param>
        /// <returns></returns>
        public IEnumerable<UserEntity> GetPageList(string queryJson, Pagination pagination)
        {
            var expression = LinqExtensions.True<UserEntity>();

            var queryParam = queryJson.ToJObject();
            if (!queryParam["B_ManaframeId"].IsEmpty())
            {
                expression = expression.And(c => c.B_ManaframeId == queryParam["B_ManaframeId"].ToString());
            }
            if (!queryParam["B_DepartmentId"].IsEmpty())
            {
                expression = expression.And(c => c.B_DepartmentId == queryParam["B_DepartmentId"].ToString());
            }
            if (!queryParam["B_Account"].IsEmpty())
            {
                expression = expression.And(c => c.B_Account.Contains(queryParam["B_Account"].ToString()));
            }
            if (!queryParam["B_RealName"].IsEmpty())
            {
                expression = expression.And(c => c.B_RealName.Contains(queryParam["B_RealName"].ToString()));
            }
            if (!queryParam["B_CreateDate"].IsEmpty())
            {
                expression = expression.And(c => c.B_CreateDate >= queryParam["B_CreateDate"][0].ToDate() && c.B_CreateDate <= queryParam["B_CreateDate"][1].ToDate());
            }
            expression = expression.And(c => c.B_SecurityLevel != 1);   //排除超管用户
            /*关联架构*/
            var userInfo = AuthenticationHelper.LoginUserInfo;
            if (!userInfo.isSystem)
            {
                var manaframeIds = _manaframe.GetSubNodes(userInfo.manaframeId);
                expression = expression.And(c => manaframeIds.IndexOf(c.B_ManaframeId) >= 0);
            }
            return BaseRepository.FindList(expression, pagination);
        }
        /// <summary>
        /// 根据架构Id及部门Id获取用户列表数据
        /// </summary>
        /// <param name="B_ManaframeId">组织架构主键</param>
        /// <param name="B_DepartmentId">部门主键</param>
        /// <param name="isDeep">是否深度获取</param>
        /// <returns></returns>
        [Caching]
        public virtual List<UserEntity> GetListByManaDepId(string B_ManaframeId, string B_DepartmentId, bool isDeep)
        {
            //是否深度查询
            if (isDeep)
            {
                var list = BaseRepository.FindList<UserEntity>(c => c.B_EnabledMark == EnabledMark.Enabled && c.B_SecurityLevel != 1)
                    .OrderBy(c => c.B_ManaframeId)
                    .AsList();

                List<UserEntity> resList = new List<UserEntity>();
                //有部门传入，获取包括子组织、子部门下所有的用户
                if (!B_DepartmentId.IsEmpty())
                {
                    var depNodes = _Department.GetSubNodes(B_ManaframeId, B_DepartmentId);

                    for (int i = 0; i < depNodes.Length(); i++)
                    {
                        resList.AddRange(list.FindAll(c => c.B_DepartmentId == depNodes[i]));
                    }
                    return resList;
                }
                //只有组织传入，获取包括子组织下所有用户
                else if (!B_ManaframeId.IsEmpty() && B_DepartmentId.IsEmpty())
                {
                    var manaNodes = _manaframe.GetSubNodes(B_ManaframeId);

                    for (int i = 0; i < manaNodes.Length(); i++)
                    {
                        resList.AddRange(list.FindAll(c => c.B_ManaframeId == manaNodes[i]));
                    }
                    return resList;
                }
                else
                {
                    return list;
                }
            }
            else
            {
                var expression = LinqExtensions.True<UserEntity>().And(c => c.B_EnabledMark == EnabledMark.Enabled);
                expression = expression.And(c => c.B_SecurityLevel != 1);   //排除超管用户
                if (!B_ManaframeId.IsEmpty())
                {
                    expression = expression.And(c => c.B_ManaframeId == B_ManaframeId);
                }
                if (!B_DepartmentId.IsEmpty())
                {
                    expression = expression.And(c => c.B_DepartmentId == B_DepartmentId);
                }
                return BaseRepository.IQueryable(expression).ToList();
            }
        }
        /// <summary>
        /// 获取实体根据账号
        /// </summary>
        /// <param name="account">账号</param>
        /// <returns></returns>
        [Caching]
        public virtual UserEntity GetEntityByAccount(string account)
        {
            return BaseRepository.FindEntity<UserEntity>(c => c.B_Account == account);
        }
        /// <summary>
        /// 获取实体根据主键
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        [Caching]
        public virtual UserEntity GetEntityById(string id)
        {
            return BaseRepository.FindEntity<UserEntity>(id);
        }
        #endregion

        #region 提交数据

        /// <summary>
        /// 保存实体(新增,编辑)
        /// </summary>
        /// <param name="formEntity"></param>
        [RemoveCache]
        public virtual (bool, string) SaveForm(UserEntity formEntity)
        {
            //字段验重
            if (ValidateExist(formEntity.B_UserId, "B_Account", formEntity.B_Account)) return (false, "账号已存在！");
            if (ValidateExist(formEntity.B_UserId, "B_EnCode", formEntity.B_EnCode)) return (false, "工号已存在！");
            if (!formEntity.B_UserId.IsEmpty())
            {
                //编辑
                formEntity.Modify();
                this.BaseRepository.Update(formEntity);
            }
            else
            {
                //新增 
                formEntity.Create();
                this.BaseRepository.Insert(formEntity);
            }
            return (true, "保存成功！");
        }
        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="formEntity"></param>
        [RemoveCache]
        public virtual (bool, string) DeleteForm(UserEntity formEntity)
        {
            this.BaseRepository.Delete(formEntity);
            return (true, "删除成功！");
        }
        /// <summary>
        /// 状态更改
        /// <summary>
        /// <param name="formEntity">数据实体</param>
        /// <returns></returns>
        [RemoveCache]
        public virtual (bool, string) ChangeState(UserEntity formEntity)
        {
            if (!formEntity.B_UserId.IsEmpty())
            {
                this.BaseRepository.Update(new UserEntity() { B_UserId = formEntity.B_UserId, B_EnabledMark = formEntity.B_EnabledMark });
                return (true, "更改成功！");
            }
            else
            {
                return (false, "更改失败！");
            }
        }
        /// <summary>
        /// 修改当前用户密码
        /// </summary>
        /// <param name="oldPassword">旧密码（MD5 小写）</param>
        /// <param name="newPassword">新密码（MD5 小写）</param>
        /// <returns></returns>
        [RemoveCache]
        public virtual (bool, string) RevisePassword(string oldPassword, string newPassword)
        {
            UserInfo userInfo = AuthenticationHelper.LoginUserInfo;
            UserEntity userEntity = this.GetEntityById(userInfo.userId);
            oldPassword = Md5Helper.Encrypt(DESEncrypt.Encrypt(oldPassword, userEntity.B_Secretkey).ToLower(), 32).ToLower();
            if (oldPassword == userEntity.B_Password)
            {
                userEntity.Modify();
                userEntity.B_Secretkey = Md5Helper.Encrypt(CommonHelper.CreateNo(), 16).ToLower();
                userEntity.B_Password = Md5Helper.Encrypt(DESEncrypt.Encrypt(newPassword, userEntity.B_Secretkey).ToLower(), 32).ToLower();
                BaseRepository.Update(userEntity);
                return (true, "修改成功，即将重新登录...");
            }
            else
            {
                return (false, "密码错误，请重新输入！");
            }
        }

        #endregion

        #region 数据验证
        /// <summary>
        /// 验证字段值是否存在
        /// </summary>
        /// <param name="id">实体主键</param>
        /// <param name="field">字段名</param>
        /// <param name="value">字段值</param>
        /// <returns></returns>
        public bool ValidateExist(string id, string field, string value)
        {
            var expression = LinqExtensions.True<UserEntity>();
            if (!string.IsNullOrEmpty(id))
            {
                expression = expression.And(t => t.B_UserId != id);
            }
            return this.BaseRepository.IQueryable(expression).Exist(field, value);
        }
        #endregion

        #region 扩展操作

        /// <summary>
        /// 验证登录 
        /// </summary>
        /// <param name="account">账号</param>
        /// <param name="password">密码 MD5 32位 小写</param>
        /// <returns></returns>
        public (bool, string) CheckLogin(string account, string password)
        {
            UserEntity userEntity = this.GetEntityByAccount(account);
            if (userEntity == null)
            {
                return (false, "账户不存在！");
            }

            if (userEntity.B_EnabledMark == EnabledMark.Enabled)
            {
                string dbPassword = Md5Helper.Encrypt(DESEncrypt.Encrypt(password.ToLower(), userEntity.B_Secretkey).ToLower(), 32).ToLower();
                if (dbPassword == userEntity.B_Password)
                {
                    return (true, "登录成功！");
                }
                else
                {
                    return (false, "密码和账户名不匹配！");
                }
            }
            else
            {
                return (false, "账户被系统锁定,请联系管理员！");
            }
        }


        /// <summary>
        /// 导入用户数据
        /// </summary>
        /// <param name="list">导入用户数据</param>
        /// <returns></returns>
        [RemoveCache]
        public virtual bool Import(List<UserEntity> list)
        {
            var db = this.BaseRepository.BeginTrans();
            try
            {
                foreach (var entity in list)
                {
                    entity.B_Password = Md5Helper.Encrypt("0000", 32);//默认密码
                    entity.Create();
                    db.Insert(entity);
                }
                db.Commit();
                return true;
            }
            catch (Exception)
            {
                db.Rollback();
                throw;
            }
        }

        #endregion

    }
}
